﻿using System;
using System.Collections.Generic;
using System.Text;
using WeiboFilter.Models;
using System.Data;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
using System.Configuration;

namespace WeiboFilter.DAL
{
    public class CustomerDAL
    {
        private string sp_getCustomerById = "dbo.getCustomerById";
        private string sp_insertCustomer = "dbo.insertCustomer";
        private string sp_updateCustomer = "dbo.updateCustomer";

        public Customer InsertCustomer(User u)
        {//当前账户如果已经在数据库中，则放弃
            Customer c = GetCustomerById(u.id);
            if (c != null)//非空则返回
            {
                return c;
            }
            else
            {
                c = new Customer();
                c.c_id = u.id;
                c.c_name = u.screen_name;
                c.c_pwd = u.id;
                c.since_id = "0";//先使用since_id把
                c.relateId = u.id;
                SqlParameter[] Params = new SqlParameter[]{
                    new SqlParameter("@c_id",c.c_id),
                new SqlParameter("@c_name",c.c_name),
                new SqlParameter("@c_pwd",c.c_pwd),
                new SqlParameter("@since_id",c.since_id),
                new SqlParameter("@relateId",c.relateId)
                };
                int ret = SqlHelper.ExecuteNonQuery(SqlCommon.connString, CommandType.StoredProcedure, sp_insertCustomer, Params);

                return c;
            }

        }

        public Customer GetCustomerById(string id)
        {
            Customer c = new Customer();
            SqlParameter[] Params = new SqlParameter[]{
                new SqlParameter("@id",id)
            };
            using(SqlDataReader sdr=SqlHelper.ExecuteReader(SqlCommon.connString,CommandType.StoredProcedure,sp_getCustomerById,Params))
            {//唯一性
                if (!sdr.HasRows)
                    return null;
                sdr.Read();
                c.c_id = sdr.GetString(0);
                c.c_name = sdr.GetString(1);
                c.c_pwd = sdr.GetString(2);
                c.since_id = sdr.GetString(3);
                c.relateId = sdr.GetString(4);
            }
            return c;
        }

        public Customer UpdateCustomer(Customer c)
        {
            SqlParameter[] Params = new SqlParameter[]{
                new SqlParameter("@c_id",c.c_id),
                new SqlParameter("@c_name",c.c_name),
                new SqlParameter("@c_pwd",c.c_pwd),
                new SqlParameter("@since_id",c.since_id),
                new SqlParameter("@relateId",c.relateId)
            };
            int ret = SqlHelper.ExecuteNonQuery(SqlCommon.connString, CommandType.StoredProcedure, sp_updateCustomer, Params);
            return c;
        }
    }
}
